﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars;

namespace DevExpress.MailClient.Win
{
    public partial class frmNewMail : PRO_DOCS.BLL.WIN.Templates.DevxMasterRibbonForm
    {
        bool isMessageModified;
        bool newMessage = true;
        readonly Data.Message SOURCE_MESSAGE;

        public frmNewMail()
        {
            InitializeComponent();
            DialogResult = DialogResult.Cancel;
        }
        public frmNewMail(Data.Message message, bool newMessage, string caption)
        {
            InitializeComponent();
            DictionaryHelper.InitDictionary(spellChecker1);
            this.newMessage = newMessage;
            DialogResult = DialogResult.Cancel;
            this.SOURCE_MESSAGE = message;
            txtSubject.Text = message.Subject;
            txtAttachmentName.Text = message.ATTACHMENT_DISPLAY_NAME;
            txtTo.Text = message.From;
            richEditControl.HtmlText = message.Text;
            this.isMessageModified = newMessage;

            if (!newMessage)
            {
                //splitContainerControl1.Collapsed = DevExpress.MailClient.Win.Data.LayoutOption.MailCollapsed;
                btnTo.Text = string.Format("{0}:", caption);
                txtTo.Properties.ReadOnly = true;
                txtSubject.Properties.ReadOnly = true;
                richEditControl.ReadOnly = true;
                btnTo.Enabled = false;
                ribbonControl.Enabled = false;
                btnSendEmail.Visible = false;

            }
            btnAttachments.Enabled = !newMessage;
            SELECTED_EMAIL_TO_LIST = new Dictionary<long, string>();
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            //if (!newMessage)
            //    DevExpress.MailClient.Win.Data.LayoutOption.MailCollapsed = splitContainerControl1.Collapsed;
        }
        public Data.Message SourceMessage { get { return SOURCE_MESSAGE; } }
        public bool IsMessageModified
        {
            get { return isMessageModified || richEditControl.Modified; }
            set
            {
                isMessageModified = value;
                richEditControl.Modified = value;
            }
        }
        #region SaveMessage event
        EventHandler onSaveMessage;
        public event EventHandler SaveMessage { add { onSaveMessage += value; } remove { onSaveMessage -= value; } }
        protected internal virtual void RaiseSaveMessage()
        {
            if (onSaveMessage != null)
                onSaveMessage(this, EventArgs.Empty);
        }
        #endregion

        void richEditControl_SelectionChanged(object sender, EventArgs e)
        {
            tableToolsRibbonPageCategory1.Visible = richEditControl.IsSelectionInTable();
            floatingPictureToolsRibbonPageCategory1.Visible = richEditControl.IsFloatingObjectSelected;
        }
        void edtTo_EditValueChanged(object sender, EventArgs e)
        {
            isMessageModified = true;
        }

        void edtSubject_EditValueChanged(object sender, EventArgs e)
        {
            isMessageModified = true;
        }
        void fileSaveItem1_ItemClick(object sender, ItemClickEventArgs e)
        {
            ApplyChanges();
        }
        void frmEditMail_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                if (QueryClose() != DialogResult.Cancel)
                    Close();
            }
        }
        void richEditControl_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Modifiers & Keys.Control) != 0 && e.KeyCode == Keys.S)
            {
                ApplyChanges();
                e.Handled = true;
            }
        }

        void frmEditMail_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = QueryClose();
            e.Cancel = result == DialogResult.Cancel;
        }
        DialogResult QueryClose()
        {
            if (!IsMessageModified)
                return DialogResult.Yes;

            DialogResult result = XtraMessageBox.Show(this, Properties.Resources.SaveQuestion, Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
            switch (result)
            {
                case DialogResult.Cancel:
                    return DialogResult.Cancel;
                case DialogResult.No:
                    return DialogResult.No;
                default:
                case DialogResult.Yes:
                    ApplyChanges();
                    return DialogResult.Yes;
            }
        }
        void ApplyChanges()
        {
            SOURCE_MESSAGE.Date = DateTime.Now;
            SOURCE_MESSAGE.Text = richEditControl.HtmlText;
            SOURCE_MESSAGE.SetPlainText(ObjectHelper.GetPlainText(richEditControl.Text.TrimStart()));
            SOURCE_MESSAGE.Subject = txtSubject.Text;
            SOURCE_MESSAGE.From = txtTo.Text;

            IsMessageModified = false;

            RaiseSaveMessage();
        }

        Dictionary<long, string> SELECTED_EMAIL_TO_LIST
        { get; set; }

        private void btnTo_Click(object sender, EventArgs e)
        {
            DevExpress.MailClient.Win.Forms.frmChooseEmailUsers chooseEmailUsers = new Forms.frmChooseEmailUsers(SELECTED_EMAIL_TO_LIST);
            if (chooseEmailUsers.ShowDialog().Equals(DialogResult.OK))
            {
                SELECTED_EMAIL_TO_LIST = chooseEmailUsers.SELECTED_EMAIL_TO_LIST;

                txtTo.Text = string.Empty;

                foreach (var item in SELECTED_EMAIL_TO_LIST)
                {
                    txtTo.Text += item.Value + "; ";
                }
            }
        }

        private void btnSendEmail_Click(object sender, EventArgs e)
        {
            Guid iNTERNAL_MAIL_ID = Guid.NewGuid();

            PRO_DOCSDatabaseDataContext.proc_INTERNAL_MAILSInsert
                (
                    iNTERNAL_MAIL_ID,
                    SOURCE_MESSAGE.Priority,
                    txtSubject.Text,
                    SOURCE_MESSAGE.From_USER_ID,
                    null,
                    richEditControl.HtmlText,
                    null
                );
            PRO_DOCSDatabaseDataContext.proc_INTERNAL_MAIL_ATTACHMENTSInsert
                (
                    Guid.NewGuid(),
                    iNTERNAL_MAIL_ID,
                    SOURCE_MESSAGE.ATTACHMENT_DISPLAY_NAME,
                    0,
                    true,
                    string.Empty,
                    SOURCE_MESSAGE.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID
                );
            foreach (var rECEIVER in SELECTED_EMAIL_TO_LIST)
            {
                PRO_DOCSDatabaseDataContext.proc_INTERNAL_MAIL_RECEIVERSInsert
                    (
                        iNTERNAL_MAIL_ID,
                        rECEIVER.Key,
                        false,
                        null,
                        false
                    );
            }

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }



        private void btnBcc_Click(object sender, EventArgs e)
        {
            Forms.frmAddMailAttachments addMailAttachments = new Forms.frmAddMailAttachments(false, SOURCE_MESSAGE);
            if (addMailAttachments.ShowDialog().Equals(DialogResult.OK))
            {

            }
        }
    }
}
